<template>
    <el-upload
            accept="image/*"
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
        <img v-if="insideUrl" :src="insideUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
</template>

<script>
    export default {
        name: "SinglePhotoUploader",
        data() {
            return {
                insideUrl: ''
            }
        },
        props: {
            // 上传的地址
            uploadUrl: {
                default: ''
            },
            // 最大大小
            maxSize: {
                default: 2
            },
            // 传入的id
            value: {
                default: -1
            },
            imgUrl: {
                default: null
            }
        },
        computed: {},
        watch: {
            imgUrl: function () {
                this.insideUrl = this.getFileUrl(this.imgUrl);
                console.log('imgUrl变化,', this.insideUrl)
            }
        },
        mounted() {
            this.insideUrl = this.getFileUrl(this.imgUrl);
            console.log('imgUrl赋值,', this.insideUrl)
        },
        methods: {
            handleAvatarSuccess(res, file) {
                console.log('上传图片之后的结果:', res, file);
                var id = res.data.id;
                this.$emit('input', id);
                this.insideUrl = this.getFileUrl(res.data.path);
            },
            beforeAvatarUpload(file) {
                const isLt2M = file.size / 1024 / 1024 < this.maxSize;
                if (!isLt2M) {
                    this.$message.error('图片大小不能超过 ' + this.maxSize + 'MB!');
                }
                return isLt2M;
            }
        }
    }
</script>

<style scoped>
    .avatar-uploader {
        width: 178px;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader:hover {
        border-color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>
